import imp
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap import utility
from util.dbUtil import fanju
from tkinter import messagebox as box
from frame.core import DataEntryForm
import os 

import abc #利用abc模块实现抽象类

class tabModel(metaclass=abc.ABCMeta):

    def treeMenu(self,event):
        '''
        表格右键菜单
        '''
        self.menubar = ttk.Menu(self.resultview)    # #创建菜单条
        # xMenu = ttk.Menu(self.menubar, tearoff=False)      # #创建子菜单
        # for item in ["子菜单1", "子菜单2", "子菜单3", "子菜单4", "子菜单5"]:
        #     xMenu.add_command(label=item)
        # self.menubar.add_cascade(label="右键总菜单1", menu=xMenu)      # #创建总菜单，将子菜单绑定进来
        self.menubar.add_command(label='修改',command=self.on_change)
        self.menubar.add_command(label='添加',command=self.on_add)
        self.menubar.add_command(label='删除',command=self.on_delete)
        self.menubar.post(event.x_root, event.y_root)

    def cleanTree(self,event):
        '''
        清空表格
        '''
        x=self.resultview.get_children()
        for item in x:
            self.resultview.delete(item)
    
    def refresh_tree(self,name=None):
        '''
        刷新表数据
        ''' 
        self.cleanTree(None)
        self.add_treeView(name)   

class fanjuTab(tabModel):
    def __init__(self,main):
        self.main=main
        self.main.fanjuTab=self  # 弹窗使用
        self.fanjudb=fanju(self.main.path)
        self.fanjuData=self.fanjudb.getAllData()

        self.name_var = ttk.StringVar(value="")
        self.init()
    
    def init(self):
        windows_tab = ttk.Frame(self.main.notebook)

        # 头部
        path_row = ttk.Frame(windows_tab)
        path_row.pack(fill=X,pady=(10,10))
        path_ent = ttk.Entry(path_row, textvariable=self.name_var)
        path_ent.pack(side=LEFT, fill=X, expand=YES, padx=20)
        path_ent.bind("<Return>", self.on_search)

        browse_btn = ttk.Button(
            master=path_row, 
            text="搜索", 
            command=self.on_search, 
            width=8
        )
        browse_btn.pack(side=LEFT, padx=(0,20))

        today_btn = ttk.Button(
            master=path_row, 
            text="今日番剧", 
            command=self.openComic, 
            width=8
        )
        today_btn.pack(side=LEFT, padx=(0,20))

        add_btn = ttk.Button(
            master=path_row, 
            text="添加", 
            command=self.on_add, 
            width=8
        )
        add_btn.pack(side=LEFT, padx=(0,20))

        #内容
        self.main.notebook.add(windows_tab, text='番剧')

        self.resultview = ttk.Treeview(
            master=windows_tab, 
            bootstyle=INFO, 
            columns=[0, 1, 2, 3,4],
            show=HEADINGS
        )
        self.resultview.pack(fill=BOTH, expand=YES,padx=10,pady=5,ipadx=10)

        #绑定事件
        # self.resultview.bind('<ButtonRelease-1>',self.clickTree) #单击
        self.resultview.bind('<Double-1>',self.openSoure) #双击 双击运行前，先执行单击
        self.resultview.bind('<3>',self.treeMenu) #右键单击

        anchorValue=CENTER
        num=0
        self.resultview.heading(num, text='编号', anchor=anchorValue)
        num+=1
        self.resultview.heading(num, text='名字', anchor=anchorValue)
        num+=1
        self.resultview.heading(num, text='时间', anchor=anchorValue)
        num+=1
        self.resultview.heading(num, text='描述', anchor=anchorValue)
        num+=1
        self.resultview.heading(num, text='状态', anchor=anchorValue)
        # self.resultview.heading(3, text='资源', anchor=anchorValue)

        num=0
        self.resultview.column(
            column=num, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 60), 
            stretch=False
        )
        num+=1        
        self.resultview.column(
            column=num, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 200), 
            stretch=False
        )
        num+=1
        self.resultview.column(
            column=num, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 60), 
            stretch=False
        )
        num+=1
        self.resultview.column(
            column=num, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 400), 
            # stretch=False
        )
        num+=1
        self.resultview.column(
            column=num, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 100), 
            stretch=False
        )
        self.add_treeView()
    
    def add_treeView(self,name=None):
        '''
        添加数据
        '''
        if self.fanjuData:
            currentday =self.main.getWeek()
            state=''
            num=1
            for one in self.fanjuData:
                one=self.fanjuData[one]
                if name:
                    if name not in one[1]:
                        continue
                if int(one[5])==0:
                    state='~完结~'
                else:
                    state='更新'
                
                if str(currentday) in one[2]:  #今日更新
                    self.resultview.insert(
                        parent='', 
                        index=END, 
                        values=(">> "+str(num),one[1], one[2], one[4], state)
                    )
                else:
                    self.resultview.insert(
                        parent='', 
                        index=END, 
                        values=(num,one[1], one[2], one[4], state)
                    )
                num+=1
    
    def openComic(self):
        '''
        打开今日番剧
        '''
        currentday =self.main.getWeek()

        num=0
        for one in self.fanjuData:
            data=self.fanjuData[one]
            if int(data[5])==0:
                continue

            if str(currentday) in data[2]:
                self.openWeb(data[3])
                num+=1

        if num<=0:
            box.showinfo(
                title='提醒', 
                message="今日无番"
            )

    def openWeb(self,data):
        '''
        打开资源
        '''
        if "," in data:
            tmp=data.split(",")
            for one in tmp:
                os.system("start "+one)
        else:
            os.system("start "+data)


    def on_search(self,event=None):
        name=self.name_var.get()
        self.refresh_tree(name) 

    def on_delete(self):
        '''
        删除数据
        '''
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[1] in self.fanjuData:
                data=self.fanjuData[txt[1]]
                if box.askyesno(title='提醒', message='确定删除 '+data[1]+" "):
                    self.fanjudb.delete(data[0])
                    del self.fanjuData[txt[1]]
                    self.refresh_tree()
       

    def edit_data(self,data):
        '''
        修改数据
        '''
        if data and len(data)>0:

            if len(data)==6:
                self.fanjudb.update(data)
            else:
                self.fanjudb.addData(data)
            self.fanjuData=self.fanjudb.getAllData()
            # 刷新表单
            self.refresh_tree()
            return True
        else:
            box.showerror(
                title='提醒', 
                message="提交数据异常"
            )
            return False
    
    def clickTree(self,event):
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            print(item,'  ',txt)

    def openSoure(self,event):
        '''
        双击打开
        '''
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[1] in self.fanjuData:
                data=self.fanjuData[txt[1]]
                self.openWeb(data[3])
    
    def on_add(self):
        self.main.top = ttk.Toplevel(self.main.win)
        self.main.top.wm_title("添加" )
        DataEntryForm(self.main)
        self.main.top.protocol("WM_DELETE_WINDOW", self._top_close)
    
    def on_change(self):
        self.main.top = ttk.Toplevel(self.main.win)
        self.main.top.wm_title("修改" )
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[1] in self.fanjuData:
                data=self.fanjuData[txt[1]]
                DataEntryForm(self.main,data)
        
        self.main.top.protocol("WM_DELETE_WINDOW", self._top_close)

    def _top_close(self):
        self.main.top.destroy()


from frame.core import applicationForm
from util.dbUtil import application
'''
应用tab
'''
class applicationTab(tabModel):
    def __init__(self,main):
        self.main=main
        self.main.applicationTab=self # 弹窗使用
        #应用
        self.applicationdb=application(self.main.path)
        self.applicationData=self.applicationdb.getAllData()

        self.name_var = ttk.StringVar(value="")
        self.init()
    
    def init(self):
        windows_tab = ttk.Frame(self.main.notebook)

        # 头部
        path_row = ttk.Frame(windows_tab)
        path_row.pack(fill=X,pady=(10,10))
        path_ent = ttk.Entry(path_row, textvariable=self.name_var)
        path_ent.pack(side=LEFT, fill=X, expand=YES, padx=20)
        path_ent.bind("<Return>", self.on_search)

        browse_btn = ttk.Button(
            master=path_row, 
            text="搜索", 
            command=self.on_search, 
            width=8
        )
        browse_btn.pack(side=LEFT, padx=(0,20))

        today_btn = ttk.Button(
            master=path_row, 
            text="一键启动", 
            command=self.startAll, 
            width=8
        )
        today_btn.pack(side=LEFT, padx=(0,20))

        add_btn = ttk.Button(
            master=path_row, 
            text="添加", 
            command=self.on_add, 
            width=8
        )
        add_btn.pack(side=LEFT, padx=(0,20))

        #内容
        self.main.notebook.add(windows_tab, text='应用')

        self.resultview = ttk.Treeview(
            master=windows_tab, 
            bootstyle=INFO, 
            columns=[0, 1, 2],
            show=HEADINGS
        )
        self.resultview.pack(fill=BOTH, expand=YES,padx=10,pady=5,ipadx=10)

        #绑定事件
        # self.resultview.bind('<ButtonRelease-1>',self.clickTree) #单击
        self.resultview.bind('<Double-1>',self.openSoure) #双击 双击运行前，先执行单击
        self.resultview.bind('<3>',self.treeMenu) #右键单击

        anchorValue=W
        self.resultview.heading(0, text='名字', anchor=anchorValue)
        self.resultview.heading(1, text='路径', anchor=anchorValue)
        self.resultview.heading(2, text='启动', anchor=anchorValue)
        # self.resultview.heading(3, text='资源', anchor=anchorValue)
        
        self.resultview.column(
            column=0, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 200), 
            stretch=False
        )
        self.resultview.column(
            column=1, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 600), 
            stretch=False
        )
        self.resultview.column(
            column=2, 
            anchor=anchorValue, 
            width=utility.scale_size(self.main.win, 100), 
            # stretch=False
        )

        self.add_treeView()
    
    def add_treeView(self,name=None):
        '''
        添加数据
        '''
        if self.applicationData:
            state=''
            for one in self.applicationData:

                one=self.applicationData[one]
                if name:
                    if name not in one[1]:
                        continue
                
                if int(one[3])==0:
                    state='~否~'
                else:
                    state='是'
                
                self.resultview.insert(
                    parent='', 
                    index=END, 
                    values=(one[1], one[2], state)
                )
    
    def startAll(self):
        '''
        一键启动
        '''
        if len(self.applicationData)>0:
            for one in self.applicationData:
                data=self.applicationData[one]
                if int(data[3])==1:
                    self.openWeb(data[2])

            if self.main.getWeek() ==5:
                self.openWeb("http://www.ruanyifeng.com/blog/")

        else:
            box.showinfo(
                title='提醒', 
                message="无待启动软件"
            )

    def openWeb(self,data):
        '''
        打开资源
        '''
        if os.path.exists(data) or data.startswith("http"):
            os.system('start '+data)
    
    
    def on_delete(self):
        '''
        删除数据
        '''
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[0] in self.applicationData:
                data=self.applicationData[txt[0]]
                if box.askyesno(title='提醒', message='确定删除 '+data[1]+" "):
                    self.applicationdb.delete(data[0])
                    del self.applicationData[txt[0]]
                    self.refresh_tree()

    def on_search(self,event=None):
        name=self.name_var.get()
        self.refresh_tree(name)

    def edit_data(self,data):
        '''
        修改数据
        '''
        if data and len(data)>0:

            if len(data)==4:
                self.applicationdb.update(data)
            else:
                self.applicationdb.addData(data)
            self.applicationData=self.applicationdb.getAllData()
            # 刷新表单
            self.refresh_tree()
            return True
        else:
            box.showerror(
                title='提醒', 
                message="提交数据异常"
            )
            return False
    
    def clickTree(self,event):
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            print(item,'  ',txt)

    def openSoure(self,event):
        '''
        双击打开
        '''
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[0] in self.applicationData:
                data=self.applicationData[txt[0]]
                self.openWeb(data[2])
    
    def on_add(self):
        self.main.top = ttk.Toplevel(self.main.win)
        self.main.top.wm_title("添加" )
        applicationForm(self.main)
        self.main.top.protocol("WM_DELETE_WINDOW", self._top_close)
    
    def on_change(self):
        self.main.top = ttk.Toplevel(self.main.win)
        self.main.top.wm_title("修改" )
        item = self.resultview.selection() #'I001'、'I002'
        if item:
            txt=self.resultview.item(item,'values')
            if txt[0] in self.applicationData:
                data=self.applicationData[txt[0]]
                applicationForm(self.main,data)
        
        self.main.top.protocol("WM_DELETE_WINDOW", self._top_close)

    def _top_close(self):
        self.main.top.destroy()